var obj;
var filterObj;

//print params
var numParam;
var params;
var header;

//post process Func
var postProcess;

//filter params
var filterIds;
var filterParams;
	
	function printReviews(){
		var newFoo = getDivDoc();
		
		$.each(filterObj, function() {
			appendText(newFoo,this);
		});
	}
	
	function filterReviews(filterParams,values){
		var newFoo = getDivDoc();
		filterObj = new Array();
		var indexCount = 0;
		$.each(obj, function() {
			if(validateValues(this,filterParams,values)){
			    filterObj[indexCount] = this;
				indexCount++;
				appendText(newFoo,this);
			}
		});
}

	function appendText(newFoo,obj){
		var element = document.createElement("div");
		var text = document.createTextNode(getTextValue(obj));
		var pre = document.createElement("pre");
		pre.appendChild(text);
		element.appendChild(pre);			
		newFoo.appendChild(element);
		if(postProcess){
			postProcess(newFoo,obj);
		}
	}

	function getDivDoc(){
		var foo = document.getElementById("abc");
		var newFoo = document.createElement("div");
		newFoo.setAttribute("class","reviews");
		foo.appendChild(newFoo);
		return newFoo;
	}

	function validateValues(obj,paramArray,values){
		if(paramArray.length ==0){
			return true;
		}
		var count = values.length;
		for(i=0;i<count;i++){
			if(!isEqual(obj[paramArray[i]],values[i])){
				return false;
			}
		}
		return true;
	}
	
	/**
	 * if source is native simply check equals
	 * if array checks if value contained in source
	 */
	function isEqual(source,value){
		if(source instanceof Array){
			if($.inArray(value, source) > -1){
				return true;
			}
		} else {
			if(source == value){
				return true;
			}
		}
		return false;
	}

	function handleJson(data){
		var lang = '';
		obj = $.parseJSON(data);
		filterObj = obj;
		printReviews();
	}
	
	function setPrintParams(head,arr){
		header = head;
		numParam = arr.length/2;
		params = arr;
	}
	
	function setFilterParams(idArray,paramArray){
		filterIds = idArray;
		filterParams = paramArray;
	}
	
	function sort(sortFn){
		$('.reviews').remove();
		filterObj.sort(sortFn);
		printReviews();
	}
	
	function getTextValue(obj){
		var textValue = header + "\n";
		for (i=0; i<numParam; i++)
		{
			textValue += "\n" + params[2*i] + ": ";
			textValue += obj[params[2*i+1]];
		}
		textValue += "\n";
		return textValue;
	}
	
	function filter(){
		$('.reviews').remove();
		var count = filterIds.length;
		var values = new Array();
		var newParams = new Array();
		var indexCount = 0;
		for(i=0;i<count;i++){
			var p = $('#' + filterIds[i]).val();
			if(p){
			   values[indexCount] = p;
			   newParams[indexCount] = filterParams[i];
			   indexCount++;
			}
		}	
		filterReviews(newParams,values);
	}
	
	function setPostProcess(func){
		postProcess = func;
	}
	
	function getJsonObject(){
		return obj;
	}